{% extends '../_manage.html' %}

{% block title %} {{ form.name }} {% endblock %}

{% block head %}

<script>
$(function () {
    getJSON('/api/categories', function (err, data) {
        if (err) {
            return fatal(err);
        }
        var categories = data.categories;
        var id = '{{ id }}';
        if (id) {
            getJSON('/api/articles/' + id, function (err, article) {
                if (err) {
                    return fatal(err);
                }
                initVM(article, categories);
            });
        }
        else {
            initVM({ id: '' }, categories);
        }
    });
});

function processFile(file, callback) {
    if (file.type!=='image/jpeg' && file.type!=='image/png') {
        alert('File is not a valid image!');
        return;
    }
    var reader = new FileReader();
    reader.onload = function(e) {
        var
            data = e.target.result;
            index = data.indexOf(';base64,');
        if ((index >= 0) && (index < 100)) {
            callback({
                image: data,
                data: data.substring(index + 8)
            });
        }
    };
    reader.readAsDataURL(file);
}

function initVM(article, categories) {
    if (article.cover_id) {
        $('#image-preview').css('background-image', 'url(/files/attachments/' + article.cover_id + '/l)');
    }
    var vm = new Vue({
        el: '#vm',
        data: {
            image: null,
            categories: categories,
            name: article.name,
            description: article.description,
            category_id: article.category_id,
            tags: article.tags,
            publish: article.publish_at ? article.publish_at.toDateTime() : '',
            content: article.content || ''
        },
        methods: {
            getPostData: function () {
                var data = {
                    name: this.name,
                    description: this.description,
                    category_id: this.category_id,
                    tags: this.tags
                }
                if (this.publish) {
                    var pt = parseDateTime(this.publish);
                    if (isNaN(pt)) {
                        throw { error: 'parameter:invalid', data: 'publish_at', message: 'Invalid publish time.'};
                    }
                    data.publish_at = pt;
                }
                var content = $('#content-editor').val();
                if (this.content !== content) {
                    data.content = content;
                }
                if (this.image !== null) {
                    data.image = this.image;
                }
                return data;
            },
            submit: function (event) {
                event.preventDefault();
                var
                    data,
                    form = $('#vm').find('form');
                try {
                    data = this.getPostData();
                }
                catch (e) {
                    form.showFormError(e);
                    return;
                }
                form.postJSON('{{ form.action}}', data, function (err, r) {
                    if (!err) {
                        window.onbeforeunload = null;
                        location.assign('{{ form.redirect }}');
                    }
                });
            }
        }
    });
    $('#loading').hide();
    $('#vm').show();

    // check content when unload:
    window.onbeforeunload = function() {
        if (vm.content !== $('#content-editor').val()) {
            return 'Content has been changed.';
        }
    };

    // fix vue select init:
    $('select[name=category_id]').val(article.category_id || '');

    $('#content-editor').val(article.content || '');
    var htmleditor = UIkit.htmleditor($('#content-editor').get(0), {
        markdown: true,
        maxsplitsize: 600
    });

    // watch file change:
    $('#file').change(function (evt) {
        evt.preventDefault();
        var f = $('#file').val();
        if (f === '') {
            // user cancelled selected file:
            vm.image = null;
            $('#image-preview').css('background-image', 'none');
            return;
        }
        try {
            var file = $('#file').get(0).files[0];
            processFile(file, function (r) {
                vm.image = r.data;
                $('#image-preview').css('background-image', 'url(' + r.image + ')');
            });
        }
        catch (e) {
            alert('Error when process file: ' + e);
        }
    });
}

</script>

{% endblock %}

{% block main %}

    <div id="loading" class="uk-width-1-1">
        <i class="uk-icon-spinner uk-icon-spin"></i> Loading...
    </div>

    <div id="vm" class="uk-width-1-1">
        <ul class="uk-tab" data-uk-tab>
            <li class="uk-active"><a href="#0">{{ _('Articles') }}</a></li>
            <li><a href="#0" onclick="location.assign('/manage/article/category_list')">{{ _('Categories') }}</a></li>
        </ul>

        <form v-on="submit: submit" class="uk-form uk-form-stacked uk-margin">
            <legend>{{ form.name }}</legend>
            <fieldset>
                <div class="uk-alert uk-alert-danger uk-hidden"></div>
                <div class="uk-form-row">
                    <label class="uk-form-label">Image:</label>
                    <div class="uk-form-controls">
                        <div id="image-preview" style="border: 1px solid #ccc; width:642px; height:362px; background-size:cover;"></div>
                    </div>
                    <div class="uk-form-controls">
                        <input id="file" type="file">
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="uk-form-label">Name:</label>
                    <div class="uk-form-controls">
                        <input v-model="name" type="text" maxlength="100" class="uk-width-1-1" placeholder="name">
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="uk-form-label">Description:</label>
                    <div class="uk-form-controls">
                        <textarea v-model="description" rows="6" class="uk-width-1-1" style="resize:none;"></textarea>
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="uk-form-label">Category:</label>
                    <div class="uk-form-controls">
                        <select name="category_id" v-model="category_id" class="uk-width-1-1">
                            <option value="">-- Select a category --</option>
                            {% raw %}
                            <option v-repeat="category: categories" value="{{ category.id }}">{{ category.name }}</option>
                            {% endraw %}
                        </select>
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="control-label">Tags:</label>
                    <div class="controls">
                        <input v-model="tags" name="tags" type="text" class="uk-width-1-1" placeholder="tag1, tag2, tag3">
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="control-label">Publish At:</label>
                    <div class="controls">
                        <input v-model="publish" name="publish_at" type="text" class="uk-width-1-1" placeholder="YYYY-MM-DD hh:mm:ss">
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="control-label">Content:</label>
                    <div class="controls">
                        <textarea id="content-editor" rows="20" style="width:100%; resize:none;"></textarea>
                    </div>
                </div>
                <div class="uk-form-row">
                    <div class="controls">
                        <button type="submit" class="uk-button uk-button-primary"><i class="uk-icon-check"></i> Save</button>
                        <button type="button" class="uk-button" onclick="location.assign('{{ form.redirect }}')"><i class="uk-icon-times"></i> Cancel</button>
                    </div>
                </div>
            </fieldset>
        </form>
    </div>

{% endblock %}
